# token.py
from functools import wraps
import jwt
import datetime
from flask import current_app,request,session,jsonify


#python自带的有为什么要自己写
# 定义生成 JWT 的函数
def generate_token(username):
    payload = {
        'username': username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)  # 设置过期时间
    }
    token = jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')
    return token.decode('utf-8')

# 定义验证 JWT 的函数
def decode_token(token):
    try:
        data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
        return data
    except jwt.ExpiredSignatureError:
        return None  # Token 过期
    except jwt.InvalidTokenError:
        return None  # Token 无效

# 中间件用于验证 JWT
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')

        if not token:
            return jsonify({'message': '缺少身份验证 Token'}), 401

        data = decode_token(token)
        if not data:
            return jsonify({'message': 'Token 无效或过期'}), 401

        return f(*args, **kwargs)

    return decorated
